<template>
  <div class="app-container">
    <div>
      <span>
        <!-- <el-input
          placeholder="请输入查询类型名称"
          v-model="queryParams.classifyName"
          clearable
          style="width: 240px"
          @clear="fetchGoodsType"
        > -->
        <el-autocomplete
          class="inline-input"
          v-model="queryParams.classifyName"
          :fetch-suggestions="querySearch"
          placeholder="请输入查询类型名称"
          value-key="classifyName"
          clearable
          @clear="fetchGoodsType"
        >
        </el-autocomplete>
        <el-button
          type="primary"
          icon="el-icon-search"
          @click="fetchGoodsType"
        >
        </el-button>
        <!-- <el-button
          slot="append"
          icon="el-icon-search"
          @click="fetchGoodsType"
        ></el-button> -->
      </span>
      <el-button
        class="btn-add"
        type="primary"
        icon="el-icon-plus"
        size="small"
        @click="handleAdd"
      >
        添加分类
      </el-button>
      <el-button
        class="btn-add"
        type="danger"
        icon="el-icon-delete"
        size="small"
        @click="delAllSelection"
      >
        批量删除
      </el-button>

      <el-card style="margin-top: 20px;" shadow="hover">
        <i class="el-icon-tickets" style="margin-top: 5px" />证书产品类型列表
        <el-table
          v-loading="loading"
          ref="multipleTable"
          :data="cateList"
          row-key="id"
          :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
          width="60%"
          @selection-change="handleSelectionChange"
          style="margin-top: 20px;"
        >
          <el-table-column
            type="selection"
            width="55"
            align="center"
          ></el-table-column>
          <!-- <el-table-column
            type="index"
            label="序号"
            width="70"
            align="center"
          /> -->
          <el-table-column
            label="类型名称"
            prop="classifyName"
            align="center"
            width="240"
          ></el-table-column>
          <el-table-column
            label="排序"
            align="center"
            prop="orderNum"
          ></el-table-column>
          <el-table-column label="操作" align="center">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="primary"
                icon="el-icon-edit"
                plain
                @click="handleUpdate(scope.row)"
                >编辑</el-button
              >
              <el-button
                size="mini"
                type="danger"
                icon="el-icon-delete"
                plain
                @click="handleDel(scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getCateList"
        />
      </el-card>
    </div>

    <!-- 添加或修改商品类别对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="55%">
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <!-- <el-form-item label="上级分类:" prop="parentId">
          <treeselect v-model="form.parentId" :options="cateOptions" :normalizer="normalizer" placeholder="选择上级分类" />
        </el-form-item> -->
        <el-form-item label="类别名称:" prop="classifyName">
          <el-input
            v-model="form.classifyName"
            placeholder="请输入证书产品类别名称"
            style="width: 65%;"
          />
        </el-form-item>
        <el-form-item label="类别排序" prop="orderNum">
          <el-input-number
            v-model="form.orderNum"
            controls-position="right"
            :min="0"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { queryGoodsCate,addGoodsCate,updateGoodsCate,delGoodsCate } from "@/api/goods/goods";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "goodsCate",
  components: { Treeselect },
  data() {
    return {
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        classifyName: ""
      },
      total: 0,

      // 多选删除
      ids: [],
      multiple: true,

      // 遮罩层
      loading: false,

      // 商品类别表格数据
      cateList: [],

      // 添加商品分类表单相关项
      open: false,
      title: "",
      cateOptions: [],
      resCateOptions: [],
      form: {},
      rules: {
        parentId: [
          { required: true, message: "证书产品上级分类为必选项", trigger: "blur" }
        ],
        classifyName: [
          { required: true, message: "证书产品类别名称不能为空", trigger: "blur" }
        ],
        orderNum: [
          { required: true, message: "证书产品类别顺序不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getCateList();
    this.getTreeselect();
  },
  methods: {
    querySearch(queryString, cb) {
      var restaurants = this.resCateOptions;
      var results = queryString ? restaurants.filter(this.createFilter(queryString)): restaurants;
      cb(results);
    },
    createFilter(queryString){
      return (restaurants) => {
        return (restaurants.classifyName.toLowerCase().indexOf(queryString.toLowerCase())===0)
      }
    },
    // 查询菜单下拉树结构
    getTreeselect() {
      queryGoodsCate({
        pageNum: 1,
        pageSize: 1000
      }).then(res => {
        this.resCateOptions = res.rows;
        this.cateOptions = [];
        const menu = { id: 0, classifyName: '主类目', children: [] };
        menu.children = this.handleTree(res.rows, "id");
        this.cateOptions.push(menu);
      });
    },
    // 转换菜单数据结构
    normalizer(node) {
      if (node.children == null || node.children == 'null'){
        delete node.children;
      }
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.classifyName,
        children: node.children
      };
    },
    // 查询指定商品类别
    fetchGoodsType() {
      this.queryParams.pageNum = 1;
      this.getCateList();
    },
    // 查询商品类别列表
    getCateList() {
      this.loading = true;
      queryGoodsCate(this.queryParams).then(res => {
        this.loading = false;
        if (res.code == 200) {
          this.total = res.total;
          this.cateList = this.handleTree(res.rows, "id");
          // this.cateList = res.rows;
        } else {
          this.msgError("查询商品类别失败！");
        }
      });
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
      this.getCateList();
    },

    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        classifyName: undefined,
        orderNum: null
      };
    },

    // 点击新增按钮
    handleAdd() {
      this.reset();
      this.getTreeselect();
      this.open = true;
      this.title = "添加类别";
    },

    // 点击修改按钮
    handleUpdate(row) {
      this.reset();
      this.getTreeselect();
      this.form = row;
      this.open = true;
      this.title = "修改类别";
    },

    // 点击提交
    submitForm() {
      this.$refs["form"].validate(valid => {
        // console.log(this.form)
        this.form.parentId = 0;
        if (valid) {
          if (this.form.id !== undefined) {
            updateGoodsCate(this.form).then(res => {
              if (res.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.form = {};
                this.getCateList();
              } else {
                this.msgError(res.msg);
              }
            });
          } else {
            addGoodsCate(this.form).then(res => {
              if (res.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.form = {};
                this.getCateList();
              } else {
                this.msgError(res.msg);
              }
            });
          }
        }
      });
    },

    // 多选框选择
    handleSelectionChange(val) {
      this.ids = val.map(item => item.id);
    },
    // 批量删除按钮
    delAllSelection() {
      if (this.ids.length == 0) {
        return this.msgError("必须选择一项进行操作！");
      } else {
        var str = this.ids.join(",");
      }
      this.$confirm("确定要删除吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.deleteData(str);
          this.ids = [];
        })
        .catch(() => {});
    },
    // 删除商品分类
    handleDel(row) {
      this.$confirm("确定要删除吗?", "提示", {
        type: "warning"
      })
        .then(() => {
          this.deleteData(row.id);
        })
        .catch(() => {});
    },
    // 删除属性分类
    deleteData(id) {
      delGoodsCate(id).then(res => {
        if (res.code == 200) {
          this.msgSuccess("删除成功");
          this.getCateList();
        } else {
          this.msgError("删除失败！");
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.btn-add {
  margin-left: 20px;
}
</style>
